package com.zzh.core;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.zzh.lib.core.HLibrary;
import com.zzh.lib.core.block.HBlocker;
import com.zzh.lib.core.lang.HStringSpannable;
import com.zzh.lib.core.listener.HFilterResultCallback;
import com.zzh.lib.core.listener.HOnClickListener;
import com.zzh.lib.core.model.HAudioFileModel;
import com.zzh.lib.core.model.HDirectoryModel;
import com.zzh.lib.core.model.HFileModel;
import com.zzh.lib.core.model.HImageFileModel;
import com.zzh.lib.core.model.HVideoFileModel;
import com.zzh.lib.core.utils.HDeviceUtils;
import com.zzh.lib.core.utils.HFileUtils;
import com.zzh.lib.core.utils.HIOUtils;
import com.zzh.lib.core.utils.HKeyboardUtils;
import com.zzh.lib.core.utils.HMediaUtils;
import com.zzh.lib.core.utils.HNetUtils;
import com.zzh.lib.core.utils.HResUtils;
import com.zzh.lib.core.utils.HSystemUtils;
import com.zzh.lib.core.utils.HTaskUtils;
import com.zzh.lib.core.utils.LogUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.function.Consumer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;

/**
 * @Date: 2020/7/17 15:59
 * @Email: zzh_hz@126.com
 * @QQ: 1299234582
 * @Author: zzh
 * @Description: 测试
 */
public class MainActivity extends AppCompatActivity {

    TextView et_text;

    //NetWatchRunnable target = null;

    RunnableScheduledFuture<?> execute;

    HBlocker mBlocker = new HBlocker();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_text = findViewById(R.id.et_text);
        LogUtils.e(HFileUtils.getPublicDCIMFile().getAbsolutePath());
        LogUtils.e("nav bar height: " + HResUtils.getNavBarHeight());
        LogUtils.e("status bar height: " + HResUtils.getStatusBarHeight());
        et_text.setText("status bar height: " + HResUtils.getStatusBarHeight() + "\n" + "nav bar height: " + HResUtils.getNavBarHeight());

        findViewById(R.id.iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBlocker.blocker()) {
                    return;
                }
                LogUtils.e("-----有效点击");
                HTaskUtils.getDefaultInstance().execute(() -> {
                    HIOUtils.safeWriteToDownloadFile("aaa.txt", "bbbbbbbbbbbbbbbb".getBytes());
                });
            }
        });

        int networkType = HNetUtils.getNetworkType();
        LogUtils.i("----networkType: " + networkType);

        findViewById(R.id.btn_start_task).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                for (int i = 0; i < 10000; i++) {
                    HTaskUtils.getSingleInstance().execute(new HRunnable(i));
                }
            }
        });

        findViewById(R.id.btn_remove_task).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                HTaskUtils.getSingleInstance().release(HTaskUtils.DEFAULT_SINGLE_TASK);
            }
        });

        findViewById(R.id.btn_select_file).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {

                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
                        PackageManager.PERMISSION_GRANTED) {
                    HMediaUtils.startMultiPicture(MainActivity.this, 10010);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                }

            }
        });
        findViewById(R.id.btn_select_picture).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                LoaderManager.enableDebugLogging(true);
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
                        PackageManager.PERMISSION_GRANTED) {
                    HMediaUtils.startSinglePicture(MainActivity.this, 10011);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                }

            }
        });

        findViewById(R.id.btn_select_document).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {

                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
                        PackageManager.PERMISSION_GRANTED) {
                    HMediaUtils.startMultiDocuments(MainActivity.this, 10012);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                }

            }
        });
        findViewById(R.id.btn_select_single_document).setOnClickListener(new HOnClickListener() {
            @TargetApi(Build.VERSION_CODES.R)
            @Override
            public void onSafeClick(View v) {

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                    if (Environment.isExternalStorageManager()) {
                        HMediaUtils.startSingleDocuments(MainActivity.this, 10013);
                    } else {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:com.zzh.core"));
                        startActivityForResult(intent, 2000);
                    }
                } else {
                    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
                            PackageManager.PERMISSION_GRANTED) {
                        HMediaUtils.startSingleDocuments(MainActivity.this, 10013);
                    } else {
                        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                    }
                }

            }
        });

        findViewById(R.id.btn_cpu).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                String[] supported64BitAbis = Build.SUPPORTED_64_BIT_ABIS;
                if (supported64BitAbis != null) {
                    for (String value : supported64BitAbis) {
                        System.out.println(value);
                    }
                }
            }
        });

        findViewById(R.id.btn_file_permission).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                System.out.println(HFileUtils.getExternalPath());

            }
        });

        findViewById(R.id.btn_get_pkg).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                String packageName = HSystemUtils.getPackageName();
                LogUtils.e(packageName);
            }
        });

        try {
            Button btn = findViewById(R.id.btn_file_miui);
            btn.setText(sendMIUI12());
        } catch (Exception exception) {
        }

        viewById = findViewById(R.id.tv_drawable_border);
        viewById.setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {

                if (flag) {
                    HResUtils.drawableTop(viewById, R.mipmap.wangzhanshezhi);
                } else {
                    HResUtils.drawableNull(viewById);
                }

                flag = !flag;

            }
        });
        /*findViewById(R.id.tv_toast).setOnClickListener(new HOnClickListener() {
            @Override
            public void onSafeClick(View v) {
                ToastUtils.setShowVae(true);
                ToastUtils.setToastView(R.layout.layout_toast);
                ToastUtils.show("测试消息提醒");
                startActivity(new Intent(MainActivity.this, DeviceInfoActivity.class));
            }
        });*/

        findViewById(R.id.tv_copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HKeyboardUtils.clip("31231");
            }
        });

        TextView tv_device_detail = findViewById(R.id.tv_device_detail);

        HStringSpannable hss = new HStringSpannable("CPU: " + HDeviceUtils.getCPUAbi());
        hss.setAllTextColor("信息", Color.RED).setAllTextSize("设备", 60);
        tv_device_detail.setText(hss);
        tv_device_detail.setMovementMethod(LinkMovementMethod.getInstance());
        findViewById(R.id.tv_xiaoxi).setOnClickListener(
                v -> {
                }
        );
    }

    TextView viewById;
    boolean flag = false;

    String sendMIUI12() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        return (String) m.invoke(systemPropertiesClass, "ro.miui.ui.version.name");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10010 && resultCode == RESULT_OK) {
            Uri fileUri = data.getData();
            String queryAbsolutePath = HMediaUtils.queryAbsolutePath(fileUri);
            LogUtils.d("--------: " + queryAbsolutePath);
        } else if (requestCode == 10011 && resultCode == RESULT_OK) {
            Uri fileUri = data.getData();
            String queryAbsolutePath = HMediaUtils.queryAbsolutePath(fileUri);
            LogUtils.d("--------: " + queryAbsolutePath);
        } else if (requestCode == 10013 && resultCode == RESULT_OK) {
            List<Uri> uris = HMediaUtils.obtainDocumentsUri(data);
            //HMediaUtils.copyFileCacheInterval(uris.get(0), "");
            HMediaUtils.obtainSingleDocuments(data);
        } else if (requestCode == 10012 && resultCode == RESULT_OK) {
            List<Uri> uris = HMediaUtils.obtainDocumentsUri(data);
            //HMediaUtils.copyFileCacheInterval(uris.get(0), "");
            HMediaUtils.obtainSingleDocuments(data);
        }


    }

    public void onClickView(View view) {
        boolean externalStorageManager = false;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            externalStorageManager = Environment.isExternalStorageManager();
            if (!externalStorageManager) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);

            }
        }

    }

    public void onClickView2(View view) {
        startActivity(new Intent(this, DeviceInfoActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HTaskUtils.release();
        HLibrary.getInstance().unRegisterWatchNetwork();
    }

    public void onClickViewFile(View view) {
        HMediaUtils.getAllFiles(this, directories -> {
            if (!directories.isEmpty()) {
                for (HDirectoryModel<HFileModel> hv : directories) {
                    for (HFileModel hf : hv.getFiles()) {
                        LogUtils.d("-----: " + hf.toString());
                    }
                }
            } else {
                LogUtils.d("------: 文件为空");
            }
        });
    }

    public void onClickViewVideo(View view) {
        HMediaUtils.getAllVideos(this, (HFilterResultCallback<HVideoFileModel>) directories -> {
            if (!directories.isEmpty()) {
                for (HDirectoryModel<HVideoFileModel> hv : directories) {
                    for (HVideoFileModel hf : hv.getFiles()) {
                        LogUtils.d("-----: " + hf.toString());
                    }
                }
            } else {
                LogUtils.d("------: 视频为空");
            }
        });
    }

    public void onClickAudioVideo(View view) {

        HMediaUtils.getAllAudios(this, directories -> {
            if (!directories.isEmpty()) {
                for (HDirectoryModel<HAudioFileModel> hv : directories) {
                    for (HAudioFileModel hf : hv.getFiles()) {
                        LogUtils.d("-----: " + hf.toString());
                    }
                }
            } else {
                LogUtils.d("------: 音频为空");
            }
        });
    }

    public void onClickLocalImage(View view) {

        HMediaUtils.getAllImages(this, directories -> {
            if (directories.isEmpty()) {
                LogUtils.d("---------图片为空");
            } else {
                directories.stream().forEach(new Consumer<HDirectoryModel<HImageFileModel>>() {
                    @Override
                    public void accept(HDirectoryModel<HImageFileModel> subModel) {
                        subModel.getFiles().stream().forEach(new Consumer<HImageFileModel>() {
                            @Override
                            public void accept(HImageFileModel hImageFileModel) {
                                LogUtils.d("-----图片：" + hImageFileModel.toString());
                            }
                        });


                    }
                });
            }
        });
    }

    Dialog dialog;

    public void onClickNullSafe(View view) {
        assert dialog != null;
        dialog.cancel();

    }

    class HRunnable implements Runnable {

        private int num;

        public HRunnable(int num) {
            this.num = num;
        }

        @Override
        public void run() {
            System.out.println("------: " + num);
        }
    }

    public void getAllRes(){

        Class<? extends Class> aClass = R.xml.class.getClass();

        

    }
}
